import Day11.d06_recommend_pb2
import Day11.d06_recommend_pb2_grpc
import grpc
import time
from concurrent.futures import ThreadPoolExecutor

# 1.自定义服务类,并集成自动生成的服务类
class UserRecommendService(Day11.d06_recommend_pb2_grpc.UserRecommendServicer):
    # 重写user_recommend方法
    def user_recommend(self, request, context):
        # 获取参数
        user_id = request.user_id
        channel_id = request.channel_id
        article_num = request.article_num
        time_stamp = request.time_stamp

        # 模拟推荐系统返回结果
        response = Day11.d06_recommend_pb2.ArticleResponse()
        response.expousre = 'expousre param'
        response.time_stamp = round(time.time()*1000)
        recommends = []

        # 组装推荐结果列表,模拟数据
        for i in range(article_num):
            recommend = Day11.d06_recommend_pb2.Recommend()
            recommend.article_id = i+1
            recommend.track.click = 'click params: {}'.format(i+1)
            recommend.track.collect = 'collect params: {}'.format(i+1)
            recommend.track.share = 'share params: {}'.format(i+1)
            recommend.track.read = 'read params: {}'.format(i+1)
            recommends.append(recommend)
        response.recommends.extend(recommends)

        return response

# 2.创建rpc服务器
server = grpc.server(ThreadPoolExecutor(max_workers=20))

# 3.把自定义的服务类对象,添加到server中
Day11.d06_recommend_pb2_grpc.add_UserRecommendServicer_to_server(UserRecommendService(),server)

# 4.绑定ip和端口
server.add_insecure_port('127.0.0.1:8888')

# 5.启动rpc服务器
server.start()

# 6.防止退出
while 1:
    time.sleep(5*60)